
package com.adtec.yxdemo.utils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import cn.hutool.core.codec.Base64;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

import com.jfinal.kit.StrKit;
import com.jfinal.log.Log;

public class YxUtil {
    // 日志对象
    public static final Log log = Log.getLog(YxUtil.class);

    /**
     * 识别验证码
     *
     * @param imgBytes
     * @param type
     * @return
     */
    public static String getCodeByImg(byte[] imgBytes, String type) {
        log.info("开始请求获取验证码...");
        JSONObject reqBody = new JSONObject();
        reqBody.put("username", "adtec");
        reqBody.put("password", "123456");
        reqBody.put("typeid", type);
        reqBody.put("image", Base64.encode(imgBytes));
        String url = "http://api.ttshitu.com/predict";

        HttpRequest.closeCookie();
        HttpResponse response = HttpUtil.createPost(url).timeout(30000).body(String.valueOf(reqBody)).execute();
        String body = response.body();
        if (StrKit.isBlank(body) || !JSONUtil.isJson(body)) {
            log.error("解析验证码失败：" + body);
            return "";
        }
        JSONObject result = JSONUtil.parseObj(body);
        if (!result.containsKey("code") || !"0".equals(result.getStr("code"))) {
            log.error("解析验证码失败：" + body);
            return "";
        }
        String code = result.getByPath("data.result", String.class);
        log.info("解析验证码成功：" + code);
        return code;
    }

    /**
     * 统一的请求方法
     *
     * @param request 请求对体
     * @param logDesc 日志描述
     * @return
     */
    public static HttpResponse excute(HttpRequest request, String logDesc, boolean needLog) {
        Long startTime = System.currentTimeMillis();
        log.info(logDesc + "请求URL:" + request.getUrl());
        log.info(logDesc + "请求:" + request.toString());
        HttpResponse response = null;

        try {
            response = request.timeout(10000).execute();
        } catch (Exception e) {
            log.error(logDesc + "请求异常：" + e.getMessage(), e);
        }
        Long useTime = System.currentTimeMillis() - startTime;
        log.info(logDesc + "响应耗时:" + useTime + "毫秒");
        if (needLog) {
            log.info(logDesc + "响应:" + response);
        }
        return response;
    }

    /**
     * 获取响应报文头中Set-Cookie的键值对
     *
     * @param response
     * @return
     */
    public static String combCookie(HttpResponse response, String oldCookie) {
        Map<String, String> cookieMap = StrKit.isBlank(oldCookie) ? new HashMap<String, String>() : str2CookieMap(oldCookie);
        cookieMap.putAll(getCookieMapFormRsp(response));
        String cookie = cookieMap2Str(cookieMap);
        return formatCookie(cookie);
    }

    /**
     * 获取响应报文头中Set-Cookie的键值对
     *
     * @param response
     * @return
     */
    public static String getCookie(HttpResponse response) {
        Map<String, String> cookieMap = getCookieMapFormRsp(response);
        String cookie = cookieMap2Str(cookieMap);
        return formatCookie(cookie);
    }

    /**
     * cookie键值对转cookie字符串
     *
     * @param cookieStr
     * @return
     */
    public static Map<String, String> str2CookieMap(String cookieStr) {
        if (StrKit.isBlank(cookieStr)) {
            return new HashMap<String, String>();
        }
        Map<String, String> map = new HashMap<String, String>();
        String[] cookies = cookieStr.split(";");
        for (String cookie : cookies) {
            int index = cookie.indexOf("=");
            if (index > 0) {
                map.put(cookie.substring(0, index), cookie.length() > index ? cookie.substring(index + 1) : "");
            }
        }
        return map;
    }

    /**
     * 格式化cookie，去掉其中的domain和expires字样
     *
     * @param cookie
     * @return
     */
    public static String formatCookie(String cookie) {
        if (StrKit.isBlank(cookie)) {
            return null;
        }
        cookie = cookie.replace("\n", ";");
        Map<String, String> cookieMap = str2CookieMap(cookie);
        cookieMap.remove("domain");
        cookieMap.remove("expires");
        cookieMap.remove("path");
        cookieMap.remove("defaultloginuser_p");
        return cookieMap2Str(cookieMap);
    }

    /**
     * cookie键值对转cookie字符串
     *
     * @param cookie
     * @return
     */
    public static String cookieMap2Str(Map<String, String> cookie) {
        if (cookie == null || cookie.keySet().size() == 0) {
            return null;
        }
        Set<String> keys = cookie.keySet();
        Iterator<String> iKeys = keys.iterator();
        StringBuffer sb = new StringBuffer();
        while (iKeys.hasNext()) {
            String key = iKeys.next();
            sb.append(key + "=" + cookie.get(key) + ";");
        }
        String cookieStr = sb.toString();
        cookieStr = cookieStr.substring(0, cookieStr.length() - 1);
        return cookieStr;
    }

    /**
     * 获取响应报文头中Set-Cookie的键值对
     *
     * @param response
     * @return
     */
    public static Map<String, String> getCookieMapFormRsp(HttpResponse response) {
        Map<String, String> cookieMap = new HashMap<>();
        Map<String, List<String>> map = response.headers();
        List<String> cookies = new ArrayList<String>();
        for (String key : map.keySet()) {
            if (key != null && key.equalsIgnoreCase("set-cookie")) {
                cookies.addAll(map.get(key));
            }
        }
        if (cookies.size() == 0) {
            return cookieMap;
        }
        for (int i = 0; i < cookies.size(); i++) {
            String cookie = cookies.get(i);
            cookie = cookie.split(";")[0];
            int index = cookie.indexOf("=");
            if (index > 0) {
                cookieMap.put(cookie.substring(0, index), cookie.length() > index ? cookie.substring(index + 1) : "");
            }
        }
        return cookieMap;
    }

    public static String getPayStutas(String status) {
        String payStatus = new String();
        switch (status) {
            case "-1":
                payStatus = "未支付";
                break;
            case "-2":
                payStatus = "废止";
                break;
            case "0":
                payStatus = "未付款";
                break;
            case "1":
                payStatus = "正在付款给药械";
                break;
            case "2":
                payStatus = "付款给药械成功";
                break;
            case "3":
                payStatus = "付款给药械失败";
                break;
            case "4":
                payStatus = "正在扣款";
                break;
            case "5":
                payStatus = "扣款失败";
                break;
            case "6":
                payStatus = "正在贷款";
                break;
            case "7":
                payStatus = "贷款失败";
                break;
            case "8":
                payStatus = "正在付款给收款人";
                break;
            case "9":
                payStatus = "付款给收款人成功";
                break;
            case "10":
                payStatus = "付款给收款人失败";
                break;
            case "20":
                payStatus = "收款人确认收款";
                break;
            case "21":
                payStatus = "已作废";
                break;
            case "22":
                payStatus = "已撤销";
                break;
            default:
                break;
        }
        return payStatus;
    }

    /**
     * 时间戳转换
     */
    public static String dataConversion(String time) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Long t = Long.parseLong(time);
        return format.format(t);
    }
}
